package it.ma.musicplayernew.bluetooth;

import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.zhongdao.swing.R;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import it.ma.musicplayernew.API;
import it.ma.musicplayernew.ContentValues;
import it.ma.musicplayernew.utils.BluetoothPaired;

/**
 * This fragment controls Bluetooth to communicate with other devices.
 */
public abstract class BluetoothChatFragment extends Fragment implements BluetoothA2DPRequester.Callback {

    private static final String TAG = "BluetoothChatFragment";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    /**
     * Name of the connected device
     */
    protected String mConnectedDeviceName = null;

    protected String mConnectedDeviceAddress = null;

    /**
     * Array adapter for the conversation thread
     */
//    protected ArrayAdapter<String> mConversationArrayAdapter;

    /**
     * Local Bluetooth adapter
     */
    private BluetoothAdapter mBluetoothAdapter = null;

    private BluetoothDevice mConnectedDevice = null;

    private BluetoothA2DPRequester bluetoothA2DPRequester;

    /**
     * Member object for the chat services
     */
    private BluetoothChatService mChatService = null;
    private AudioManager mAudioManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            FragmentActivity activity = getActivity();
            Toast.makeText(activity, "蓝牙设备未能开启", Toast.LENGTH_LONG).show();
            activity.finish();
        }

    }


    @Override
    public void onStart() {
        super.onStart();
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else if (mChatService == null) {
            setupChat();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mChatService != null) {
            mChatService.stop();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }

            //尝试连接历史记录
            if(mChatService.getState() != BluetoothChatService.STATE_CONNECTED){
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constants.SP_CONFIG, Context.MODE_APPEND);
                String address = sharedPreferences.getString(Constants.ADDRESS_KEY, "");
                String name = sharedPreferences.getString(Constants.NAME_KEY, "");
                if(!TextUtils.isEmpty(address)){
                    mConnectedDeviceAddress = address;
                    mConnectedDeviceName = name;
                    toConnectedDevice(false);
                    Toast.makeText(getActivity(), "正在连接 " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                }
            }

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return onCreateUI(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        onFindView(view);
    }

    /**
     * Set up the UI and background operations for chat.
     */
    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(getActivity(), mHandler);

        onSetupUI();

    }


    /**
     * 创建ui
     */
    protected abstract View onCreateUI(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    /**
     * 初始化ui
     * @param view
     */
    protected abstract void onFindView(View view);

    /**
     * 设置ui
     */
    protected abstract void onSetupUI();

    /**
     * Makes this device discoverable.
     */
    private void ensureDiscoverable() {
        if (mBluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     *
     * @param message A string of text to send.
     */
    protected boolean sendMessage(String message) {
        if(ContentValues.UI_DEBUG){
            return true;
        }
        if(mChatService == null){
            return false;
        }
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
            //跳到连接设别界面
            connectDeviceInsecure();
            return false;
        }

        if(ContentValues.D) {
            Log.d(TAG, message);
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);
            return true;
        }
        return false;
    }

    /**
     * 在成功调用ChatService to write 一个message后， 但这是不一定是成功发送到蓝牙模块
     * @param message
     */
    protected abstract void onAfterSendMessage(String message);

    /**
     * 读到信息
     * @param message
     */
    protected abstract void onReadMessage(String message);

    /**
     * Updates the status on the action bar.
     *
     * @param resId a string resource ID
     */
    private void setStatus(int resId) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(resId);
    }

    /**
     * Updates the status on the action bar.
     *
     * @param subTitle status
     */
    protected void setStatus(CharSequence subTitle) {
        FragmentActivity activity = getActivity();
        if (null == activity) {
            return;
        }
        final ActionBar actionBar = activity.getActionBar();
        if (null == actionBar) {
            return;
        }
        actionBar.setSubtitle(subTitle);
    }

    protected void onConnected(String deviceName){
        if(bluetoothA2DPRequester == null){
            bluetoothA2DPRequester = new BluetoothA2DPRequester(this);
            bluetoothA2DPRequester.request(getActivity(), mBluetoothAdapter);
        }
    }

    @Override
    public void onA2DPProxyReceived(BluetoothA2dp proxy) {
        Method connect = getConnectMethod();
        BluetoothDevice device = mConnectedDevice;

        //If either is null, just return. The errors have already been logged
        if (connect == null || device == null) {
            return;
        }

        try {
            connect.setAccessible(true);
            connect.invoke(proxy, device);
        } catch (InvocationTargetException ex) {
            Log.e(TAG, "Unable to invoke connect(BluetoothDevice) method on proxy. " + ex.toString());
        } catch (IllegalAccessException ex) {
            Log.e(TAG, "Illegal Access! " + ex.toString());
        }
    }

    /**
     * Wrapper around some reflection code to get the hidden 'connect()' method
     * @return the connect(BluetoothDevice) method, or null if it could not be found
     */
    private Method getConnectMethod () {
        try {
            return BluetoothA2dp.class.getDeclaredMethod("connect", BluetoothDevice.class);
        } catch (NoSuchMethodException ex) {
            Log.e(TAG, "Unable to find connect(BluetoothDevice) method in BluetoothA2dp proxy.");
            return null;
        }
    }

    /**
     * The Handler that gets information back from the BluetoothChatService
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            FragmentActivity activity = getActivity();
            switch (msg.what) {
                case Constants.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothChatService.STATE_CONNECTED:
                            setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                            onConnected(mConnectedDeviceName);
//                            mConversationArrayAdapter.clear();
                            break;
                        case BluetoothChatService.STATE_CONNECTING:
                            setStatus(R.string.title_connecting);
                            break;
                        case BluetoothChatService.STATE_LISTEN:
                        case BluetoothChatService.STATE_NONE:
                            setStatus(R.string.title_not_connected);
                            break;
                    }
                    break;
                case Constants.MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
//                    mConversationArrayAdapter.add("Me:  " + writeMessage);

                    onAfterSendMessage(writeMessage);

                    break;
                case Constants.MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    //AT#2112*   //正常情况
                    //AT#2112*AT#656*  //两个完整命令连在一起    AT#2112   AT#656*
                    //AT#2112*AT#656  //两个命令连在一起  但最后的那个不完整
                    //AT#2112AT#656*  //两个命令连在一起  但前面的那个不完整
                    //2112AT#656  //两个命令连在一起  两个都不完整
                    try {
                        //长度
                        int len = msg.arg1;
                        printByteArr(readBuf, len);
                        String readMessage;
                        readMessage = new String(readBuf, 0, len);
                        int endIndex = -1;
                        String substring;
                        String[] split = readMessage.split(API.BASE);
                        for (String string : split) {
                            endIndex = string.indexOf(API.END_CHART);
                            if (endIndex > -1) {
                                substring = API.BASE + string.substring(0, endIndex);
                                if (ContentValues.D) Log.i(TAG, " substring : " + substring);
//									if(substring.startsWith(CMDUtils.MUSIC_NAME_HEAD)){ //歌名信息
//										substring = getMusicName(substring, CMDUtils.getMusicEncoding(readMessage));
//									}
                                onReadMessage(substring);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (ContentValues.D) Log.e(TAG, "split readMessage error!!" + e.toString());
                    }
                    // construct a string from the valid bytes in the buffer
                    //String readMessage = new String(readBuf, 0, msg.arg1);
//                    mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);
                    //onReadMessage(readMessage);
                    break;
                case Constants.MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
                    if (null != activity) {
                        Toast.makeText(activity, "已连接"
                                + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    }
                    saveConnectedDeviceAddress();
                    onConnected(mConnectedDeviceName);
                    break;
                case Constants.MESSAGE_TOAST:
                    if (null != activity) {
                        Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private void saveConnectedDeviceAddress() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constants.SP_CONFIG, Context.MODE_APPEND);
        sharedPreferences.edit().putString(Constants.ADDRESS_KEY, mConnectedDeviceAddress)
                .putString(Constants.NAME_KEY, mConnectedDeviceName)
                .commit();
    }

    private void printByteArr(byte[] readBuf, int len) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < len; i++) {
            sb.append(readBuf[i]);
            if(i == len -1){
                sb.append("]");
            }else{
                sb.append(", ");
            }

        }
        if(ContentValues.D) Log.i(TAG, " >>> " + sb.toString());
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE_SECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, true);
                }
                break;
            case REQUEST_CONNECT_DEVICE_INSECURE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    connectDevice(data, false);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occurred
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
                            Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
        }
    }

    /**
     * Establish connection with other divice
     *
     * @param data   An {@link Intent} with {@link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
     * @param secure Socket Security type - Secure (true) , Insecure (false)
     */
    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        mConnectedDeviceAddress = data.getExtras()
                .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object

        toConnectedDevice(secure);

    }

    private void toConnectedDevice(boolean secure) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mConnectedDeviceAddress);

        //1.匹配
        try {
//            ClsUtils.setPin(device.getClass(), device, String.valueOf(SystemClock.currentThreadTimeMillis())); // 手机和蓝牙采集器配对
//            ClsUtils.createBond(device.getClass(), device);
//            ClsUtils.cancelPairingUserInput(device.getClass(), device);
            BluetoothPaired.createBond(device.getClass(), device);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "配对 "+ mConnectedDeviceName +" 失败", Toast.LENGTH_SHORT).show();
            return;
        }

        mConnectedDevice = device;

        //2.连接
        mChatService.connect(device, secure);
    }

    private void connectDeviceInsecure() {
        // Launch the DeviceListActivity to see devices and do scan
        Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
    }

    private void connectDeviceSecure() {
        // Launch the DeviceListActivity to see devices and do scan
        Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
        startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
    }

}
